<template>
  <el-dialog
    draggable
    overflow
    v-model="visible"
    :title="titleMap[mode]"
    :width="1024"
    destroy-on-close
    @closed="$emit('closed')"
  >
    <sc-water-mark ref="wm" text="已审核" :color="'rgba(128,128,128,0.1)'">
      <el-form
        :model="form"
        :rules="rules"
        ref="dialogForm1"
        label-width="70px"
        label-position="top"
        class="formhead"
      >
        <el-row style="display: flex; align-items: center">
          <el-col :span="18" :column="4">
            <span style="font-size: 25px">{{ titleOrder }}</span>
            <span style="color: red; padding-left: 10px">{{ order_code_string }}</span>
          </el-col>
          <el-col :span="6">
            <el-descriptions direction="vertical">
              <el-descriptions-item
                label="编号"
                label-align="center"
                align="center"
                label-class-name="light-blue"
              >
                <el-input v-model="form.code" disabled placeholder="自动生成"></el-input
              ></el-descriptions-item>
              <el-descriptions-item
                label="单据日期"
                label-align="center"
                align="center"
                label-class-name="light-blue"
              >
                <el-date-picker
                  v-model="form.billdate"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  disabled
                />
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
      </el-form>
      <!-- <sc-water-mark ref="wm" text="已审核" subtext="誉卓纱线"> -->
      <sk-tabs type="border-card">
        <el-tab-pane ref="tab" label="基础信息">
          <el-form
            :model="form"
            :rules="rules"
            ref="dialogForm"
            label-width="70px"
            label-position="right"
          >
            <el-row>
              <el-col :span="13">
                <el-row>
                  <el-col :span="8" align="客户">
                    <el-form-item label="客户" prop="customer_id">
                      <skAutoChoose
                        :disabled="form.iscustomer == 1"
                        v-model="form.customer.name"
                        :params="[
                          {
                            name: {
                              type: 'nlr',
                              value: 'YZ',
                            },
                          },
                        ]"
                        :name="'customer'"
                        :assign="form"
                        @select="cunstomerSelect"
                      >
                      </skAutoChoose>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" align="联系人">
                    <el-form-item label="联系人" prop="linkman_id" class="addicon">
                      <el-select v-model="form.linkman_id" :placeholder="'先选择客户'">
                        <el-option
                          v-for="item in linkmanList"
                          :value="item.id"
                          :label="item.name + ',' + item.phone"
                          :key="item.id"
                        >
                        </el-option>
                      </el-select>
                      <el-button
                        type="info"
                        icon="ElIconPlus"
                        @click="linkmanAdd"
                        style="width: 22px; height: 24px"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="理单人" prop="singler_id">
                      <skAutoChoose
                        v-model="form.singler.name"
                        :name="'user'"
                        :asKey="'singler_id'"
                        :assign="form"
                      >
                      </skAutoChoose>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-row>
                      <el-col :span="8">
                        <el-form-item label="派车单" prop="car_id">
                          <skAutoChoose
                            v-model="form.car.code"
                            :name="'car'"
                            :assign="form"
                            @select="selectCar"
                          >
                          </skAutoChoose>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="运输商" prop="car.company_id">
                          <skAutoChoose
                            v-model="form.car.company.name"
                            :name="'factory'"
                            :asKey="'company_id'"
                            :assign="form.car"
                            :params="[{ category_id: 54 }]"
                          >
                          </skAutoChoose>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="运费" prop="car.amount">
                          <el-input v-model="form.car.amount" clearable></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="8">
                        <el-form-item label="搬运单" prop="carry_id">
                          <skAutoChoose
                            v-model="form.carry.code"
                            :name="'carry'"
                            :assign="form"
                            @select="selectCarry"
                          >
                          </skAutoChoose>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="搬运人" prop="carry.company_id">
                          <skAutoChoose
                            v-model="form.carry.company.name"
                            :name="'factory'"
                            :asKey="'company_id'"
                            :assign="form.carry"
                            :params="[{ category_id: 55 }]"
                          >
                          </skAutoChoose>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="搬运费" prop="carry.amount">
                          <el-input v-model="form.carry.amount" clearable></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item label="备注" prop="remark">
                      <el-input v-model="form.remark" clearable></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="11">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="欠款" prop="code">
                      <el-input label="账户剩余" v-model="ARBalance" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="额度" prop="code">
                      <el-input
                        label="客户额度"
                        v-model="credit_limit"
                        clearable
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="是否含税" prop="tax_id">
                      <el-switch
                        v-model="form.tax_id"
                        :active-value="1"
                        :inactive-value="0"
                      ></el-switch>
                    </el-form-item>
                  </el-col>
                  <el-col :span="18">
                    <el-form-item label="付款抬头" prop="billtrade" class="addicon">
                      <el-select v-model="form.billtrade" :placeholder="'先选择客户'">
                        <el-option
                          v-for="item in billtradeList"
                          :value="item.name"
                          :label="item.name"
                          :key="item.name"
                        >
                        </el-option>
                      </el-select>
                      <el-button
                        type="info"
                        icon="ElIconPlus"
                        @click="billtradeAdd"
                        :color="'red'"
                        style="width: 22px; height: 24px"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="收款">
                      <sc-form-table
                        ref="table"
                        v-model="form.collection"
                        :addTemplate="addTemplate"
                        placeholder="无收款数据"
                        style="height: 100px; overflow-y: auto; background: "
                      >
                        <el-table-column prop="time" label="收款金额" width="100">
                          <template #default="scope">
                            <el-input
                              v-model="scope.row.amount"
                              :disabled="scope.row.status_id == 1"
                            ></el-input>
                          </template>
                        </el-table-column>
                        <el-table-column prop="type" label="收款银行卡" width="130">
                          <template #default="scope">
                            <sk-select-group
                              v-model="scope.row.subject_id"
                              :list="accountList"
                              :disabled="scope.row.status_id == 1"
                              @select="(data) => subjectSelect(data, scope.row)"
                            />
                          </template>
                        </el-table-column>
                        <el-table-column prop="val" label="收款日期" width="120">
                          <template #default="scope">
                            <el-date-picker
                              v-model="scope.row.billdate"
                              type="date"
                              placeholder="选择收款日期"
                              value-format="YYYY-MM-DD"
                              :disabled="scope.row.status_id == 1"
                            />
                          </template>
                        </el-table-column>
                      </sc-form-table>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-form>

          <sc-VxeTable
            ref="save"
            :gridEvts="gridEvts"
            :data="form.details"
            :gridOps="gridOps"
            :height="300"
            :tablecode="'market_retail_save'"
          >
          </sc-VxeTable>
        </el-tab-pane>
        <el-tab-pane label="附件">
          <sk-upload
            v-model="form.attachments"
            :limit="10"
            draggable
            tip="单个文件不要超过10M,请上传图像格式文件"
          >
          </sk-upload>
        </el-tab-pane>
      </sk-tabs>
    </sc-water-mark>
    <!-- </sc-water-mark> -->
    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button
        type="primary"
        v-if="form.status_id == 0"
        :loading="isSaveing"
        @click="submit()"
        >保 存</el-button
      >
    </template>
  </el-dialog>
  <linkman-add ref="saveDialog" @success="handleSuccess"> </linkman-add>
  <billtrade-add ref="billtradeDialog" @success="billtradeSuccess"> </billtrade-add>
  <skBrowserChoose
    v-model="openChooseDlg"
    :name="'storage_browser'"
    @close="openChooseDlg = false"
    @select="additems"
    :params="getParams"
  >
  </skBrowserChoose>
</template>

<script>
import skBrowserChoose from "@/components/skBrowserChoose";
import linkmanAdd from "./linkmanAdd";
import billtradeAdd from "./billtradeAdd";
import skDicSelect from "@/components/skDicSelect";
import skAutoChoose from "@/components/skAutoChoose";
import skSelectGroup from "@/components/skSelectGroup";
import XEUtils from "xe-utils";
export default {
  emits: ["success", "closed"],
  components: {
    skAutoChoose,
    skDicSelect,
    linkmanAdd,
    skBrowserChoose,
    skSelectGroup,
    billtradeAdd,
  },
  data() {
    return {
      mode: "add",
      dialog: { save: false },
      openChooseDlg: false,
      order_code: [],
      ARBalance: 0,
      titleOrder: "零售发货",
      credit_limit: 0,
      gridEvts: {
        choose: () => (this.openChooseDlg = true),
      },
      iscustomer: null,
      titleMap: {
        add: "新增",
        edit: "编辑",
      },
      linkmanList: [],
      billtradeList: [],
      form: {
        id: "",
        car: { company: {} },
        carry: { company: {} },
        status_id: 0,
        customer_id: null,
        customer: { name: "" },
        linkman: { name: "" },
        linkman_id: "",
        singler: { name: "" },
        collection: [],
        department_id: 0,
        singler_id: 0,
        billdate: XEUtils.toDateString(new Date(), "yyyy-MM-dd"),
        code: "",
        remark: "",
        details: [],
        attachments: [],
      },
      addTemplate: {
        billdate: XEUtils.toDateString(new Date(), "yyyy-MM-dd"),
        state: 1,
        trade_id: 0,
      },
      rules: {
        billdate: { required: true, message: "请选择单据日期" },
        customer_id: { required: true, message: "请选择客户" },
        linkman_id: { required: true, message: "请选择联系人" },
      },
      accountList: [],
      visible: false,
      isSaveing: false,
      gridOps: {
        height: 300,
        columns: [
          {
            field: "auxiliary_quantity",
            event: {
              keyup: ({ row, params }) => {
                row["quantity"] = row["auxiliary_quantity"] * 25;
                row["se_quantity"] = row["quantity"];
                row["se_auxiliary_quantity"] = row["auxiliary_quantity"];
                row["amount"] = (row["se_quantity"] * row["price"]).toFixed(2);
                params.$grid.updateFooter();
              },
            },
          },
          {
            field: "se_auxiliary_quantity",
            event: {
              keyup: ({ row, params }) => {
                row["se_quantity"] = row["se_auxiliary_quantity"] * 25;
                row["amount"] = (row["se_quantity"] * row["price"]).toFixed(2);
                params.$grid.updateFooter();
              },
            },
          },
          {
            field: "se_quantity",
            event: {
              keyup: ({ row, params }) => {
                row["amount"] = (row["se_quantity"] * row["price"]).toFixed(2);
                params.$grid.updateFooter();
              },
            },
          },
          {
            field: "price",
            event: {
              keyup: ({ row, params }) => {
                row["amount"] = (row["se_quantity"] * row["price"]).toFixed(2);
                params.$grid.updateFooter();
              },
            },
          },
          {
            field: "amount",
            event: {
              keyup: ({ row, params }) => {
                row["price"] = (row["se_quantity"] * row["price"]).toFixed(2);
                params.$grid.updateFooter();
              },
            },
          },
        ],
      },
    };
  },
  mounted() {
    this.getAccount();
  },

  computed: {
    order_code_string() {
      return this.order_code.toString();
    },
  },
  watch: {
    "form.details": {
      handler(val) {
        this.form.iscustomer = null;
        this.order_code = [];
        val.map((row) => {
          if (!this.order_code.includes(row.order_code)) {
            this.order_code.push(row.order_code);
          }
        });
      },
      deep: true,
    },
    "form.iscustomer"(value) {
      if (value != 1) {
        this.titleOrder = "零售发货";
      }
    },
    "form.collection": {
      handler(val) {
        if (val.some((row) => row.tax_id == 1)) {
          this.rules.billtrade = { required: true, message: "公账请选择付款抬头！" };
        } else {
          this.rules.billtrade = {};
        }
      },
      deep: true,
    },
  },
  methods: {
    getParams() {
      let params = {};
      if (this.form.iscustomer != null) {
        params = { iscustomer: this.form.iscustomer };
      }
      if (this.form.iscustomer == 1) {
        params.company_id = this.form.customer_id;
      }
      return [params];
    },
    selectCarry(data) {
      if (typeof data.code == "undefined") {
        data = { company: {} };
        this.form.carry_id = 0;
      }
      this.form.carry = data;
    },
    selectCar(data) {
      if (typeof data.code == "undefined") {
        data = { company: {} };
        this.form.car_id = 0;
      }
      this.form.car = data;
    },
    loadDefaultLinkMan() {
      let userInfo = this.$TOOL.data.get("USER_INFO");
      this.handleSuccess({
        id: userInfo.employee_id,
        name: userInfo.username,
        phone: userInfo.phone,
      });
    },
    additems(items) {
      this.openChooseDlg = false;

      items.map((defrow) => {
        let row = this.$TOOL.objCopy(defrow);
        row.id = "key" + row.id;
        if (this.form.iscustomer == null) {
          this.form.iscustomer = row.iscustomer;
        }
        if (this.form.iscustomer != row.iscustomer) {
          return this.$message.error("库存不能同时选择客户库存和备货库存！");
        }
        if (this.form.iscustomer == 1) {
          this.getOrderByDyeLot(row.dyelot, row.company_id, row.color_id).then((v) => {
            if (v.data.main ?? false) {
              row.order_code = v.data.main.code;
              row.order_detail_id = v.data.id;
              row.price = v.data.price;
              //报价单号 由订单带过来
              row.offer_code = v.data.offer_code;
              row.promotion_code = v.data.promotion_code;
              row.amount = v.data.price * row.available_quantity;

              this.titleOrder = "订单发货";
              this.form.customer_id = v.data.main.customer_id;
              this.cunstomerSelect(v.data.main.customer);
              this.form.customer = v.data.main.customer;
            } else {
              this.$message.error("库存无法确定订单，请手动选择需要发货的客户！");
              this.form.iscustomer = 0;
            }
            this.pushDetail(row);
          });
        } else this.pushDetail(row);
        return row;
      });
    },
    pushDetail(row) {
      row["auxiliary_quantity"] = XEUtils.toNumber(row["available_auxiliary_quantity"]);
      row["quantity"] = XEUtils.toNumber(row["available_quantity"]);

      row["se_auxiliary_quantity"] = row["auxiliary_quantity"];
      row["se_quantity"] = row["quantity"];
      this.form.details.push(row);
    },
    getOrderByDyeLot(dyelot, customer_id, color_id) {
      return this.$API.pro.plan.getOrderByDyelot.get({
        dyelot: dyelot,
        company_id: customer_id,
        color_id: color_id,
      });
    },
    linkmanAdd() {
      this.$refs.dialogForm.validateField("customer_id", (err) => {
        if (err) {
          this.$refs.saveDialog
            .setData(this.form.customer.name, this.form.customer_id)
            .open("add");
        }
      });
    },
    linkmanGet(company_id) {
      this.$API.basedata.businessCompany.linkmanGet
        .get({
          filter: [{ company_id: company_id }],
        })
        .then((v) => {
          this.linkmanList = v.data;
        });
    },
    billtradeGet(company_id) {
      this.$API.basedata.businessCompany.billtradeGet
        .get({
          filter: [{ company_id: company_id }],
        })
        .then((v) => {
          this.billtradeList = v.data;
        });
    },
    billtradeAdd() {
      this.$refs.dialogForm.validateField("customer_id", (err) => {
        if (err) {
          this.$refs.billtradeDialog
            .setData(this.form.customer.name, this.form.customer_id)
            .open("add");
        }
      });
    },
    subjectSelect(data, row) {
      row.trade_id = data.trade_id;
      //盘点是否有票
      if (data.trade_id == 1000) {
        row.tax_id = 0;
      } else {
        row.tax_id = 1;
      }

      if (typeof row.billdate == "undefined")
        row.billdate = XEUtils.toDateString(new Date(), "yyyy-MM-dd");
      this.tryToSetBilltrade();
    },
    getAccount() {
      this.$API.basedata.subject.list
        .get({ filter: [{ parent_id: 1002 }] })
        .then((res) => {
          this.accountList = res.data;
        });
    },
    tryToSetBilltrade() {
      if (this.billtradeList.length == 1 && this.form.tax_id == 1) {
        this.form.billtrade = this.billtradeList[0].name;
      } else {
        this.form.billtrade = null;
      }
    },
    cunstomerSelect(data) {
      let userInfo = this.$TOOL.data.get("USER_INFO");
      this.linkmanList = data.link_mans ?? [];
      this.billtradeList = data.billtrade ?? [];
      this.credit_limit = data.credit_limit;
      this.ARBalance = data.ARBalance;
      this.form.singler = data.employee ?? userInfo;
      this.form.singler_id = data.employee_id ?? userInfo.id;

      this.form.department_id = data.employee?.department_id ?? userInfo.department_id;
      //初始化联系人
      if ((data.link_mans ?? []).length == 0) {
        this.loadDefaultLinkMan();
      } else {
        this.linkmanList = data.link_mans;
        this.form.linkman_id = this.linkmanList[0].id;
      }
      this.tryToSetBilltrade();
    },

    //显示
    open(mode = "add") {
      this.mode = mode;

      this.visible = true;
      this.$nextTick(() => {
        if (this.form.status_id == 1) {
          this.$refs.wm.create();
        } else {
          this.$refs.wm.clear();
        }
      });
      return this;
    },
    handleSuccess(data) {
      this.linkmanList.push(data);
      this.form.linkman_id = data.id;
    },
    billtradeSuccess(data) {
      this.billtradeList.push(data);
      this.form.billtrade = data.name;
    },
    //表单提交方法
    submit() {
      this.$refs.dialogForm1.validate((valid) => {
        if (valid)
          this.$refs.dialogForm.validate(async (valid) => {
            if (valid) {
              this.isSaveing = true;

              var res = await this.$API.market.retail.save.post(this.form);
              this.isSaveing = false;
              if (res.code == 200) {
                this.$emit("success", this.form, this.mode);
                this.visible = false;
                this.$message.success("操作成功");
              }
            }
          });
      });
    },
    async getItems(code) {
      var res = await this.$API.market.retail.details.get({
        filter: [{ code: code }],
      });
      if (res.code == 200) {
        this.form.details = res.data.rows;
      }
    },

    //表单注入数据
    async setData(data) {
      for (let i in data) {
        if (data[i] === null) delete data[i];
      }
      delete data.details;
      Object.assign(this.form, data);
      this.linkmanGet(this.form.customer_id);
      this.billtradeGet(this.form.customer_id);
      await this.getItems(this.form.code);
    },
  },
};
</script>

<style>
.addicon .el-select {
  width: calc(100% - 24px);
}

.addicon .el-input__wrapper {
  border-top-right-radius: 0px;
  border-bottom-right-radius: 0px;
}

.addicon .el-button--small {
  border-top-left-radius: 0px;
  border-bottom-left-radius: 0px;
}
</style>
